package com.weijianhuawen.wjblog.common.mail;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @version: java version 8
 * @Author: weijianhuawen
 * @description:
 * @date: 2024-12-09 22:16
 */

@Component
@Slf4j
public class MailHelper {
    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private JavaMailSender javaMailSender;

    public Boolean sendHtml(String to, String title, String html) {
        log.info("【邮件消息Helper】 开始发送邮件......");

        // 生成消息体
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper = null;
        try {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            // 邮件发送方
            mimeMessageHelper.setFrom(mailProperties.getUsername());
            // 邮件接收方
            mimeMessageHelper.setTo(to);
            // 设置标题
            mimeMessageHelper.setSubject(title);
            // 设置邮件内容
            mimeMessageHelper.setText(html, true);
            // 发送邮件
            javaMailSender.send(mimeMessage);
            log.info("【邮件消息Helper】 邮件成功发送至：{}，发送主题：{}，发送内容：{}", to, title, html);
        } catch (Exception e) {
            log.warn("【邮件消息Helper】 邮件发送异常，发送目标：{}, 异常原因：{}", to, e.getMessage());
            return false;
        }

        return true;
    }

    // 判断邮件格式是否正确
    public static Boolean validateEmail(String email) {
        try {
            InternetAddress internetAddress = new InternetAddress(email);
            internetAddress.validate();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
